#include "draggablebutton.h"
#include <QApplication>
#include <QDebug>
#include <QDrag>
#include <QMimeData>

DraggableButton::DraggableButton(const QString &text, QWidget *parent) : QPushButton(text, parent)
{}

DraggableButton::~DraggableButton() {}

void DraggableButton::mouseDoubleClickEvent(QMouseEvent *event)
{
    //    qDebug() << __FUNCTION__;
    if (event->button() == Qt::LeftButton) {
        emit doubleClicked();
    }

    QPushButton::mouseDoubleClickEvent(event);
}

void DraggableButton::mousePressEvent(QMouseEvent *event)
{
    //    qDebug() << event->button();
    //    qDebug() << event->pos();
    if (event->button() == Qt::LeftButton) {
        m_dragStartPosition = event->pos();
    }
    QPushButton::mousePressEvent(event);
}

void DraggableButton::mouseMoveEvent(QMouseEvent *event)
{
    //    qDebug() << event->button();
    //    qDebug() << event->pos();
    if (!(event->buttons() & Qt::LeftButton)) {
        return;
    }
    if ((event->pos() - m_dragStartPosition).manhattanLength() < QApplication::startDragDistance()) {
        return;
    }

    // 创建一个 QMimeData 对象
    QMimeData *mimeData = new QMimeData;
    auto filepath = property("filepath").toString();
    mimeData->setText(filepath);

    QUrl url = QUrl::fromLocalFile(filepath.mid(8));
    qDebug() << url;
    mimeData->setUrls({url});

    // 创建一个 QDrag 对象
    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);

    // 可选：设置拖拽图像
    QPixmap pixmap = this->grab();
    drag->setPixmap(pixmap);
    drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));

    // 开始拖拽操作
    Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
    //    auto dropAction = drag->exec(Qt::LinkAction);
    qDebug() << dropAction;
    if (dropAction == Qt::MoveAction) {
        qDebug() << "deleteLater";
        deleteLater(); // 删除按钮
    }
}
